# coding: utf-8
'''
Created on May 26, 2010

@author: guard
'''

import os
from warnings import warn

class PLUGIN_CATEGORIES:
    GAME = 1
    TOURNAMENT = 2

class PLUGIN_TYPES:
    MAIN = 1
    ADDITIONAL = 2
    TOTAL = 3

def uid(category, type):
    return '{0}.{1}'.format(category, type)

class BasePlugin(object):
    category = None
    type = None
    
    full_name = u''
    marker = u''
    description = u''
    
    @staticmethod
    def calculate(*params): 
        raise NotImplementedError

    
class PluginsRegister(object):
    ACCEPTABLE_COMBINATIONS = (
        (PLUGIN_CATEGORIES.GAME, PLUGIN_TYPES.MAIN),              # основной показатель в игре
        (PLUGIN_CATEGORIES.GAME, PLUGIN_TYPES.ADDITIONAL),        # дополнительный показатель в игре
        (PLUGIN_CATEGORIES.GAME, PLUGIN_TYPES.TOTAL),             # общий ("хитрый") обсчет игры
        (PLUGIN_CATEGORIES.TOURNAMENT, PLUGIN_TYPES.MAIN),        # обсчет турнира - основной показатель
        (PLUGIN_CATEGORIES.TOURNAMENT, PLUGIN_TYPES.ADDITIONAL),  # обсчет турнира - дополнительный показатель
    )
    
    _register = {}
    for (i, j) in ACCEPTABLE_COMBINATIONS:
        _register[uid(i, j)] = []
    _register_by_name = {}
            
    @classmethod
    def register(cls, plugin_cls):
        id = uid(plugin_cls.category, plugin_cls.type)
        if id not in cls._register: 
            warn(u'{2}: неверная комбинация категории ({0}) и типа ({1}) плагина'.format(plugin_cls.category,
                                                                                         plugin_cls.type,
                                                                                         plugin_cls.__name__),
                 ImportWarning)
        else:
            cls._register[id].append(plugin_cls)
            cls._register_by_name[plugin_cls.__name__] = plugin_cls

    @classmethod
    def plugins(cls, category, type):
        return cls._register.get(uid(category, type))
        
    @classmethod
    def plugin_by_name(cls, name):
        return cls._register_by_name.get(name)
    
    
    @staticmethod
    def autodiscover():
        op = os.path
        dir = op.dirname(__file__)
        files = os.listdir(dir)
        pluginfiles = [fname[:-3] for fname in files if fname.endswith(".py") and fname != '__init__.py'] + \
                      [fname for fname in files if op.isdir(op.join(fname, dir)) 
                       and op.exists(op.join(fname, dir, '__init__.py'))]
        __import__(__package__, fromlist=pluginfiles)        
        for plugin_cls in BasePlugin.__subclasses__():
            PluginsRegister.register(plugin_cls)